# -*- coding: utf-8 -*-
"""
Flask应用启动脚本
@api-version: 1.0.0
"""

import os
import sys
from flask_sqlalchemy import SQLAlchemy

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from backend.app import create_app
from backend.models import db
from backend.init_db import init_database

def main():
    """主函数"""
    # 创建Flask应用
    app = create_app()
    
    with app.app_context():
        try:
            # 检查数据库连接
            db.engine.execute('SELECT 1')
            print("[SUCCESS] Database connection successful")
            
            # 检查表是否存在
            from sqlalchemy import inspect
            inspector = inspect(db.engine)
            tables = inspector.get_table_names()
            
            if not tables or 'users' not in tables:
                print("[INIT] Initializing database...")
                init_database()
                print("[SUCCESS] Database initialization completed")
            else:
                print("[SUCCESS] Database tables already exist")
                
        except Exception as e:
            print(f"[ERROR] Database connection failed: {str(e)}")
            print("Please check database configuration and connection information")
            return False
    
    # 启动应用
    print("[START] Starting Flask application...")
    print(f"[URL] Service address: http://localhost:5000")
    print(f"[URL] API address: http://localhost:5000/api")
    print(f"[URL] Health check: http://localhost:5000/api/health")
    print("Press Ctrl+C to stop the service")
    print("=" * 50)
    
    try:
        app.run(
            host='0.0.0.0',
            port=5000,
            debug=True,
            use_reloader=True  # Enable auto-reload for debugging
        )
    except KeyboardInterrupt:
        print("\n[STOP] Service stopped")
    except Exception as e:
        print(f"[ERROR] Service startup failed: {str(e)}")
        return False
    
    return True

if __name__ == '__main__':
    main()